<?php
/**
 * 会员等级
 */
namespace app\api\model;
use app\common\model\BlockchainOrder as BlockchainOrderModel;
use app\common\model\MemberLevel as MemberLevelModel;
use app\common\model\Member as MemberModel;
use app\common\common;
use app\common\model\DrawLog as DrawLogModel;
use app\api\model\MemberArithmeticalPower as MemberArithmeticalPowerModel;
use app\common\model\UserMoneyLog;
use think\cache\driver\Redis;
use app\common\model\TriggerContract as TriggerContractModel;

class MemberLevel extends MemberLevelModel
{
    //用户升级
    public static function upgrade($mid)
    {
        //查询用户详情
        $member = MemberModel::getDetails($mid);
        if ($member['level_id'] == 0) {   //升级为默认等级
            $level = self::getDefault();
            MemberModel::upgrade_level($mid, $level['id']);
        }
        if ($member['level_id'] != 0) {
            //获取当前用户等级详情
            $level = self::getDetails($member['level_id']);
            $level_num = $level['level'] + 1;
            //获取下一级等级
            $upgrade_level = self::getLevelDetails($level_num);

            $krAmount = 0;

            if (empty($upgrade_level)) return false;
            $upgrade_level = $upgrade_level->toArray();
            $status = true;    //升级状态

            if ($upgrade_level['matrix'] == 1) {  //需要完成矩阵
                $juzhen = common::member_matrix($mid);
                foreach ($juzhen as $v) {
                    if (empty($v['id'])) $status = false;
                }
            }

            if ($status && $upgrade_level['pay_mining'] == 1) {  //需要购买矿机
                $list = MemberArithmeticalPower::getList($mid,1,20,['pay_status'=>1])->toArray();
                if(empty($list['data'])) $status = false;
            }

            //支付升级
            if($upgrade_level['shop_pay'] == 1 && $upgrade_level['pay_amount'] > 0){
                //查询支付列表
               $order_list = BlockchainOrderModel::appoint_info($mid,'level',$upgrade_level['id']);
               $amount = 0;

               //统计金额
               foreach ($order_list as $o){
                   $amount = bcadd($amount,$o['money'],8);
                   $event_data = json_decode($o['event_data'],true);
                   if(empty($event_data['krAmount'])) $event_data['krAmount'] = 0;
                   $krAmount = bcadd($krAmount,$event_data['krAmount']/(10**18),8);
               }

               if($amount < $upgrade_level['pay_amount']) $status = false;
            }

            //开启直推
            if ($status && $upgrade_level['push'] == 1) {
                //查询我的伞下用户
                $push_member = MemberModel::member_relationship($mid, 1);
                $status = !empty($push_member['all']) ? self::upgrade_condition($push_member, $upgrade_level['push_num'], $upgrade_level['push_level']) : false;
            }

            //判断你是否开启了间推
            if ($status && $upgrade_level['interposition'] == 1) {
                //查询我的伞下用户
                $interposition_member = MemberModel::member_relationship($mid, 2);
                $status = !empty($interposition_member['all']) ? self::upgrade_condition($interposition_member, $upgrade_level['interposition_num'], $upgrade_level['interposition_level']) : false;
            }

            $iteam_member = '';
            //判断你是否开启了团队
            if ($status && $upgrade_level['team'] == 1) {

                if($upgrade_level['team_thread'] == 0){ //判断是否有开启多线程
                    //查询我的伞下用户
                    $iteam_member = MemberModel::member_relationship($mid);
                    $status = !empty($iteam_member['all']) ? self::upgrade_condition($iteam_member, $upgrade_level['team_num'], $upgrade_level['team_level']) : false;
                }else{
                    //开启多线程
                    if($upgrade_level['team_num'] > 0){
                        $push_member = MemberModel::member_relationship($mid, 1);

                        //判断直推人数 是否满足
                        if(count($push_member['all']) < $upgrade_level['team_num']){
                            $status = false;
                        }else{

                            $status = false;
                            $push = [];
                            $team_num = 0;

                            foreach ($push_member['all'] as $v){    //执行多线程查询

                                if($v['level'] != $upgrade_level['team_level']){
                                    $iteam_member = MemberModel::member_relationship($v['id']);
                                    $team_thread_status = !empty($iteam_member['all']) ? self::upgrade_condition($iteam_member, 1, $upgrade_level['team_level']) : false;
                                }else{
                                    $team_thread_status = true;
                                }

                                if($team_thread_status){
                                    $team_num += 1;
                                }
                                if($team_num >= $upgrade_level['team_num']) $status = true;
                                if($status) break;  //终止foreach循环
                            }

                        }
                    }
                }
            }

            //判断你是否开启了团队算力
            if ($status && $upgrade_level['team_computing'] > 0){

                $redis = new Redis(config('cache.stores.redis'));
                $team_total = 0;

                $team_data = $redis->get('user_power_'.$mid);
                if(!empty($team_data)){
                    $team_data = json_decode($team_data,true);
                    $team_total = $team_data['team_nozhiya'];
                }

                $status = $upgrade_level['team_computing'] <= $team_total ? true : false;
            }

            //升级用户
            if ($status) {
                //升级用户
                MemberModel::upgrade_level($mid, $upgrade_level['id']);
                //活动抽奖
                if ($upgrade_level['draw'] > 0) {
                    //发放抽奖资格
                    for ($i = 0; $upgrade_level['draw'] > $i; $i++) {
                        DrawLogModel::add($mid, 'Member upgrade', $upgrade_level['id'], '恭喜用户升级到：' . $upgrade_level['name'] . ',获得抽奖：' . $upgrade_level['draw'] . '次');
                    }
                }
                //升级代币奖励
                if($upgrade_level['upgradation_cid'] > 0 && $upgrade_level['upgradation_num'] > 0){
                    $currency = Currency::getDetails($upgrade_level['upgradation_cid']);
                    if(!empty($currency)){
                         //cto 市场需要，临时改成10倍LP
                        //UserMoneyLog::change($mid,$currency['name'],$upgrade_level['upgradation_num'],'Upgrade rewards','','用户升级：'.$upgrade_level['name'].',奖励'.$currency['name'].':'.$upgrade_level['upgradation_num'].'个');
                        $lp_num=bcmul($upgrade_level['upgradation_num'],10,8);
                        UserMoneyLog::change($mid,$currency['name'], $lp_num,'Upgrade rewards','','用户升级：'.$upgrade_level['name'].',奖励'.$currency['name'].':'.$lp_num.'个');
                    }
                }
                //用户算力奖励
                if($upgrade_level['power'] > 0){
                    //发放用户算力
                    MemberModel::upPower($mid,$upgrade_level['power']);
                }

                //发放KR奖励
                if($krAmount > 0){
                    common::upgrade_dividend($mid,$upgrade_level['id'],$krAmount,$amount);
                }

                //添加用户兑换比例
                if($upgrade_level['kr_limitation'] > -1){
                    $member_trigger = TriggerContractModel::newOneInfo($mid,'level kr');
                    //已添加触发信息不为空,且未达到触发条件
                    if(empty($member_trigger) || $member_trigger['num'] != $upgrade_level['kr_limitation']){
                        //用户限制
                        $tc_data =[
                            'mid'   =>  $mid,
                            'type'  =>  'level kr',
                            'num'   =>  $upgrade_level['kr_limitation'],
                            'association_id'    =>  $upgrade_level['id'],
                            'addtime'   =>  date('Y-m-d H:i:s',time()),
                        ];
                        TriggerContractModel::insert($tc_data);
                    }
                }

            }

        }
    }

    /**
     * 升级条件是否满足
     * @param $member   我伞下用户
     * @param $condition_num    最少人数
     * @param int $condition_level  等级限制
     */
     protected static function upgrade_condition($member,$condition_num,$condition_level = 0){
        //计算我的伞下人数
        $num = sizeof($member['all']);
        //伞下人数不足
        if($num < $condition_num) return false;

        //判断是否有限制伞下等级
        if($condition_level > 0){
            $push_level = 0;    //满足等级人数
            //循环直推用户
            foreach ($member['all'] as $v){
                //判断等级大于或等于 设定等级
                if($v['level'] >= $condition_level) $push_level += 1;
            }
            //判断伞下用户等级数量是否足够
            if($push_level < $condition_num) return false;
        }
        return true;
    }

    /**
     * 获取再下一级
     * @param $level_id
     */
    public static function Higher_level($level_id){
        $level = self::where('id',$level_id)->find();
        $hLevel = self::where('level',$level['level']+1)->find();
        return $hLevel;
    }

}